package cn.mily.user.service.impl;

import cn.mily.basics.constant.Constant;
import cn.mily.basics.exception.UtilException;
import cn.mily.basics.utils.JsonResult;
import cn.mily.user.constans.WechatConstans;
import cn.mily.user.domain.LoginInfo;
import cn.mily.user.domain.WXuser;
import cn.mily.user.domain.dto.RegInfoDto;
import cn.mily.user.mapper.LoginInfoMapper;
import cn.mily.user.mapper.WechatMapper;
import cn.mily.user.service.IWechatService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WechatServiceImpl implements IWechatService {

    @Autowired
    private WechatMapper mapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    String token = UUID.randomUUID().toString();
    String wxopenid = null;

    @Override
    @Transactional
    public JsonResult getWechatToken(String code){
        GetMethod getMethod = null;

        try {
            //创建Http客户端
            HttpClient client = new HttpClient();
            String getTokenurl = WechatConstans.ACCESSTOKENURL.replace("APPID", WechatConstans.APPID)
                    .replace("SECRET", WechatConstans.SECRET).replace("CODE", code);
            //创建一个get方法
            getMethod = new GetMethod(getTokenurl);
            //执行get方法
            getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf8");
            // 3 通过客户端传入请求就可以发起请求,获取响应对象
            client.executeMethod(getMethod);
            // 4 提取响应json字符串返回
            String result = new String(getMethod.getResponseBodyAsString().getBytes("utf8"));
            /*al工具类将json字符串转成json对象 */
            JSONObject jsonObject = JSONObject.parseObject(result);
            /*获取json中的 token 和 微信用户唯一表示 */
            String accessToken = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            String getWechatMsg = WechatConstans.getWechatUserMsg.replace("ACCESS_TOKEN", accessToken)
                    .replace("OPENID", openid);
            //创建一个get方法
            getMethod = new GetMethod(getWechatMsg);
            //执行get方法
            getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf8");
            // 3 通过客户端传入请求就可以发起请求,获取响应对象
            client.executeMethod(getMethod);
            // 4 提取响应json字符串返回
            String result2 = new String(getMethod.getResponseBodyAsString().getBytes("utf8"));
            /*al工具类将json字符串转成json对象 */
            JSONObject jsonObject2 = JSONObject.parseObject(result2);
            /*获取json中的 token 和 微信用户唯一表示 */
            /*判断微信登录表中是否有当前用户*/
            wxopenid = jsonObject.getString("openid");
            WXuser wxuser = mapper.findByOpenId(wxopenid);
            if(wxuser==null){/*当前用户没有登录过  在wxuser表中创建该对象*/
                /*封装对象*/
                WXuser wXuser = createWxuser(jsonObject2);
                /*存储表中*/
                mapper.add(wXuser);
            }/*不为null 当前用户用微信登录过*/
            /*判断loginInfo有无值微信绑定了网站用户 redis中保存token  返回登录成功*/
            if(wxuser!=null&&wxuser.getLoginInfo_id()!=null){
                LoginInfo loginInfo = wxuser.getLoginInfo_id();
                /*将用户数据存在redis中*/
                redisTemplate.opsForValue().set(token,loginInfo,15L, TimeUnit.MINUTES);
                JsonResult jsonResult = new JsonResult();
                jsonResult.setResultObj(token);
                return jsonResult;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            /*关闭*/
            getMethod.releaseConnection();
        }
        /* 没有绑定  返回状态  前端跳转绑定页面*/
        JsonResult openid = new JsonResult("openid");
        openid.setResultObj(wxopenid);
        return openid;
    }

    /**
     * 绑定微信 用户
     * @param loginInfo
     */
    @Override
    @Transactional
    public JsonResult bangder(RegInfoDto regInfo) throws UtilException {
        /*验证手机号填写*/
        if(regInfo.getPhone()==null){
            throw new UtilException("请填写手机号！");
        }
        /*验证验证码填写*/
        if(regInfo.getVerCode()==null){
            throw new UtilException("请填写验证码！");
        }
        /*验证验证码正确*/
        /*从redis中获取验证码*/
        String s = (String)redisTemplate.opsForValue().get(regInfo.getPhone()+":"+Constant.USER_BANDER);
        if(!regInfo.getVerCode().equals(s.split(":")[0])){
            throw new UtilException("抱歉验证码错误！");
        }
        /* 根据手机号和 type查询 有无用户*/
        LoginInfo login = loginInfoMapper.loginByUserName(regInfo.getPhone(), regInfo.getType());
        /*获取wxuser*/
        WXuser xuser = mapper.findByOpenId(regInfo.getOpenid());
        /*有当前用户  进行微信绑定*/
        if(login!=null){
            xuser.setLoginInfo_id(login);
            mapper.updata(xuser);
            redisTemplate.opsForValue().set(token,login );
        }else{/*没有当前用户*/
            LoginInfo loginInfo = new LoginInfo();
            BeanUtils.copyProperties(regInfo, loginInfo);
            /*创建用户*/
            loginInfoMapper.add(loginInfo);
            xuser.setLoginInfo_id(loginInfo);
            /*更新微信表*/
            mapper.updata(xuser);
            redisTemplate.opsForValue().set(token,loginInfo);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setResultObj(token);
        return jsonResult;
    }

    /**
     * 封装微信用户
     * @param jsonObject2 用户的json对象数据
     * @return 封装完成的对象
     */
    private WXuser createWxuser(JSONObject jsonObject2) {
        WXuser wXuser = new WXuser();
        /*微信用户唯一标识*/
        wXuser.setOpenid(jsonObject2.getString("openid"));
        /*昵称*/
        wXuser.setNickname(jsonObject2.getString("nickname"));
        /*性别*/
        wXuser.setSex(jsonObject2.getString("sex"));
        /*地址*/
        wXuser.setAddress(jsonObject2.getString("country")+"/"+jsonObject2.getString("province")+"/" +jsonObject2.getString("city"));
        /*头像*/
        wXuser.setHeadimgurl(jsonObject2.getString("headimgurl"));
        /*登录信息*/
        return wXuser;
    }
}
